package com.atguigu.gulimall.product.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * TODO 加入这个配置，会导致在前端传入时间戳进行区分请求时，json解析异常，无法对号t字段
 */
//@Configuration
public class MvcConfig implements WebMvcConfigurer {

    /**
     * 重写消息转换器
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(mappingJackson2HttpMessageConverter());
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        /**
         * 通过该方法对mapper对象进行设置，所有序列化的对象都将按该规则进行序列化
         *     Include.Include.ALWAYS 默认，都不转换
         *     Include.NON_DEFAULT 属性为默认值，则不序列化
         *     Include.NON_EMPTY 属性为空("") 或者为NULL ，则不序列化
         *     Include.NON_NULL 属性为NULL，则不序列化
         */
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(
                new ObjectMapper().
                        setSerializationInclusion(JsonInclude.Include.NON_EMPTY));
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        return converter;
    }
}